package com.maycurobj.service.http;

import com.alibaba.fastjson.JSONObject;
import com.maycur.developer.sdk.common.api.MaycurOpenApiClient;
import com.maycur.developer.sdk.common.api.MaycurPlatform;
import com.maycur.developer.sdk.common.exception.MaycurException;
import com.maycur.developer.sdk.common.profile.MaycurAPIProfile;
import com.maycur.developer.sdk.maycur.ultimate.openapi.request.auth.PostAuthLoginRequest;
import com.maycur.developer.sdk.maycur.ultimate.openapi.response.auth.PostAuthLoginResponse;
import com.maycurobj.configuration.ConfInfo;
import lombok.Data;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Data
@Slf4j
public class MaycurApiService {

    @Autowired
    private ConfInfo confInfo;

    @Autowired
    private CloseableHttpClient httpClient;

    @Autowired
    private RequestConfig config;

    // MaycurOpenApiClient 请保持单例，内部存储访问接口所需的token，多例情况会导致token覆盖冲突
    private MaycurOpenApiClient client;
    //体外公司
    private MaycurOpenApiClient clientSide;

    // 获取调用每刻sdk平台的client
    public synchronized MaycurOpenApiClient getMaycurOpenApiClient() {
        MaycurAPIProfile profile = MaycurAPIProfile.createProfile(confInfo.getOpenApiUrl(), confInfo.getOpenApiAppCode(), confInfo.getOpenApiAppSecret());

//        System.out.println("参数："+confInfo.getOpenApiUrl()+"---"+confInfo.getOpenApiAppCode()+"---"+confInfo.getOpenApiAppSecret());

        if (client == null) {
            // 设置目标平台，请看枚举：ULTIMATE旗舰独立版，INTERNATIONAL国际版，DINGDING旗舰钉钉版
            profile.setPlatform(MaycurPlatform.ULTIMATE);
            client = new MaycurOpenApiClient(profile);
        }
        System.out.println("client 内存地址：" + System.identityHashCode(client));
        return client;
    }

    // 获取调用杰毅每刻sdk平台的client
    public synchronized MaycurOpenApiClient getMaycurOpenApiClientSide() {
        MaycurAPIProfile profile = MaycurAPIProfile.createProfile(confInfo.getOpenApiUrl(), confInfo.getOpenApiAppCodeSide(), confInfo.getOpenApiAppSecretSide());

//        System.out.println("参数："+confInfo.getOpenApiUrl()+"---"+confInfo.getOpenApiAppCode()+"---"+confInfo.getOpenApiAppSecret());

        if (clientSide == null) {
            // 设置目标平台，请看枚举：ULTIMATE旗舰独立版，INTERNATIONAL国际版，DINGDING旗舰钉钉版
            profile.setPlatform(MaycurPlatform.ULTIMATE);
            clientSide = new MaycurOpenApiClient(profile);
        }
        System.out.println("client 内存地址：" + System.identityHashCode(clientSide));
        return clientSide;
    }

    /**
     * 获取token
     *
     * @return
     */
    public JSONObject getToken() {
        Long timestamp = System.currentTimeMillis();
        String secret = DigestUtils.sha256Hex(confInfo.getOpenApiAppSecret() + ":" + confInfo.getOpenApiAppCode() + ":" + timestamp);
        PostAuthLoginRequest request = new PostAuthLoginRequest();
        request.setAppCode(confInfo.getOpenApiAppCode());
        request.setSecret(secret);
        request.setTimestamp(timestamp);
        try {
            PostAuthLoginResponse rsp = getMaycurOpenApiClient().execute(request);
            return JSONObject.parseObject(JSONObject.toJSONString(rsp.getData()));
        } catch (MaycurException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 体外公司获取token
     *
     * @return
     */
    public JSONObject getTokenSide() {
        Long timestamp = System.currentTimeMillis();
        String secret = DigestUtils.sha256Hex(confInfo.getOpenApiAppSecretSide() + ":" + confInfo.getOpenApiAppCodeSide() + ":" + timestamp);
        PostAuthLoginRequest request = new PostAuthLoginRequest();
        request.setAppCode(confInfo.getOpenApiAppCodeSide());
        request.setSecret(secret);
        request.setTimestamp(timestamp);
        try {
            PostAuthLoginResponse rsp = getMaycurOpenApiClientSide().execute(request);
            return JSONObject.parseObject(JSONObject.toJSONString(rsp.getData()));
        } catch (MaycurException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 带参数的post请求(每刻专用)
     * 如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @param str
     * @return
     * @throws Exception
     */
    public String doPostForMaycur(String url, JSONObject header, String str) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        // 加入配置信息
        httpPost.setConfig(config);

        if (str != null) {

            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
            httpPost.setHeader("tokenId", header.getString("tokenId"));
            httpPost.setHeader("entCode", header.getString("entCode"));
            // 判断map是否为空，不为空则进行遍历，封装from表单对象
            StringEntity stringEntity = new StringEntity(str, "utf-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);

            // 发起请求
            CloseableHttpResponse response = this.httpClient.execute(httpPost);
            String ret = EntityUtils.toString(response.getEntity(), "UTF-8");
            if (StringUtils.isNotBlank(ret)) {

                return ret;
            } else {
                return null;
            }
        }
        return null;
    }

    /**
     * 带参数的post请求(每刻专用)
     * 如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doGetForMaycur(String url, JSONObject header) throws Exception {
        // 声明httpPost请求
        HttpGet httpGet = new HttpGet(url);
        // 加入配置信息
        httpGet.setConfig(config);

        httpGet.setHeader("Content-Type", "application/json;charset=utf-8");
        httpGet.setHeader("tokenId", header.getString("tokenId"));
        httpGet.setHeader("entCode", header.getString("entCode"));
        // 判断map是否为空，不为空则进行遍历，封装from表单对象
//            StringEntity stringEntity = new StringEntity(str, "utf-8");
//            stringEntity.setContentEncoding("UTF-8");
//            httpGet.setEntity(stringEntity);

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);
        String ret = EntityUtils.toString(response.getEntity(), "UTF-8");
        if (StringUtils.isNotBlank(ret)) {

            return ret;
        } else {
            return null;
        }
    }

    /**
     * put请求(每刻专用)
     * 如果状态码为200，则返回body，如果不为200，则返回null
     *
     * @param url
     * @return
     * @throws Exception
     */
    public String doPutForMaycur(String url, JSONObject header,String str) throws Exception {
        // 声明httpPost请求
        HttpPut httpPut = new HttpPut(url);
        // 加入配置信息
        httpPut.setConfig(config);

        httpPut.setHeader("Content-Type", "application/json;charset=utf-8");
        httpPut.setHeader("tokenId", header.getString("tokenId"));
        httpPut.setHeader("entCode", header.getString("entCode"));

        StringEntity stringEntity = new StringEntity(str, "utf-8");
        stringEntity.setContentEncoding("UTF-8");
        httpPut.setEntity(stringEntity);

        // 发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpPut);
        String ret = EntityUtils.toString(response.getEntity(), "UTF-8");
        if (StringUtils.isNotBlank(ret)) {

            return ret;
        } else {
            return null;
        }
    }

}
